package com.xk857.simpleeffect.fragment.main;

import static android.app.Activity.RESULT_OK;
import static android.content.Context.MODE_PRIVATE;
import static java.lang.String.format;

import android.Manifest;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.provider.Settings;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.android.material.bottomsheet.BottomSheetDialog;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.scwang.smart.refresh.footer.BallPulseFooter;
import com.scwang.smart.refresh.header.BezierRadarHeader;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.xk857.simpleeffect.R;
import com.xk857.simpleeffect.activity.AboutActivity;
import com.xk857.simpleeffect.activity.AddMatterActivity;
import com.xk857.simpleeffect.activity.FriendListActivity;
import com.xk857.simpleeffect.activity.LoginActivity;
import com.xk857.simpleeffect.activity.OpinionActivity;
import com.xk857.simpleeffect.activity.SettingActivity;
import com.xk857.simpleeffect.activity.ShareCodeActivity;
import com.xk857.simpleeffect.activity.StudyActivity;
import com.xk857.simpleeffect.activity.UpdatePasswordActivity;
import com.xk857.simpleeffect.activity.UpdatePersonMeActivity;
import com.xk857.simpleeffect.adapter.ListMatterAdapter2;
import com.xk857.simpleeffect.db.PersonDataBase;
import com.xk857.simpleeffect.domain.Result;
import com.xk857.simpleeffect.domain.entity.AddFriendShare;
import com.xk857.simpleeffect.domain.entity.Customer;
import com.xk857.simpleeffect.domain.entity.Matter;
import com.xk857.simpleeffect.domain.param.AddMatterParam;
import com.xk857.simpleeffect.domain.vo.MatterListVO;
import com.xk857.simpleeffect.enums.RequestEnum;
import com.xk857.simpleeffect.utils.OkHttpUtils;
import com.xuexiang.xqrcode.XQRCode;
import com.xuexiang.xqrcode.util.QRCodeAnalyzeUtils;
import com.xuexiang.xui.adapter.simple.XUISimpleAdapter;
import com.xuexiang.xui.utils.DensityUtils;
import com.xuexiang.xui.widget.dialog.bottomsheet.BottomSheet;
import com.xuexiang.xui.widget.dialog.materialdialog.MaterialDialog;
import com.xuexiang.xui.widget.popupwindow.popup.XUIListPopup;
import com.xuexiang.xui.widget.popupwindow.popup.XUIPopup;
import com.xuexiang.xui.widget.toast.XToast;
import com.xuexiang.xutil.app.PathUtils;
import com.xuexiang.xutil.tip.ToastUtils;

import java.lang.reflect.Type;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.function.Consumer;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.StrUtil;

public class PersonFragment extends Fragment {
    private View view;
    private ImageView pictureImgView;
    private TextView nickNameText;
    private TextView cardNumText;
    private int page;

    private List<MatterListVO> matterList;

    private RecyclerView matterListView;
    private RefreshLayout refreshLayout;

    private final String[] iconStrItems = new String[]{"默认", "学习", "工作", "运动", "生活", "社交"};
    private LinearLayout teachLayout;
    private LinearLayout friendLayout;
    private LinearLayout opinionLayout;
    private LinearLayout sweepLayout;
    private LinearLayout settingLayout;
    private LinearLayout aboutLayout;
    private LinearLayout logoutLayout;
    private int REQUEST_CODE_SCAN = 6;
    private static final int PICK_IMAGE_REQUEST = 1; // onActivityResult回调码
    private static final int MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE = 2; // 动态权限申请回调码

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.main_fragment_person, container, false);
        initView();
        initBasic();
        initData();
        initRefresh();
        return view;
    }

    // 基本设置
    private void initBasic() {
        // 使用说明
        teachLayout = view.findViewById(R.id.teach_layout);
        // 好友管理
        friendLayout = view.findViewById(R.id.friend_layout);
        // 意见反馈
        opinionLayout = view.findViewById(R.id.opinion_layout);
        // 扫一扫
        sweepLayout = view.findViewById(R.id.sweep_layout);
        // 我的设置
        settingLayout = view.findViewById(R.id.setting_layout);
        // 关于我们
        aboutLayout = view.findViewById(R.id.about_layout);
        // 退出登录
        logoutLayout = view.findViewById(R.id.logout_layout);

        logoutLayout.setOnClickListener(v -> {
            if (getActivity() != null) {
                new MaterialDialog.Builder(getActivity()).iconRes(R.drawable.icon_info).title(R.string.info).content("您确定要退出登录吗？")
                        .positiveText(R.string.yes).negativeText(R.string.cancel).onPositive((dialog, which) -> {
                            PersonDataBase.removePersonInfo(getActivity());
                            getActivity().startActivity(new Intent(getActivity(), LoginActivity.class));
                        }).show();
            }
        });

        sweepLayout.setOnClickListener(v -> {
            new BottomSheet.BottomListSheetBuilder(getActivity())
                    .addItem("扫一扫")
                    .addItem("从相册选择")
                    .setIsCenter(true)
                    .setOnSheetItemClickListener((dialog, itemView, position, tag) -> {
                        dialog.dismiss();
                        if (getActivity() != null) {
                            if (position == 0) {
                                // 扫一扫
                                XQRCode.startScan(this, REQUEST_CODE_SCAN);
                            } else if (position == 1) {
                                // 从相册选择
                                showFileChooser();
                            }
                        }
                    })
                    .build()
                    .show();
        });

        aboutLayout.setOnClickListener(v -> startActivity(new Intent(getActivity(), AboutActivity.class)));
        teachLayout.setOnClickListener(v -> startActivity(new Intent(getActivity(), StudyActivity.class)));
        friendLayout.setOnClickListener(v -> startActivity(new Intent(getActivity(), FriendListActivity.class)));
        settingLayout.setOnClickListener(v -> startActivity(new Intent(getActivity(), SettingActivity.class)));
        opinionLayout.setOnClickListener(v -> startActivity(new Intent(getActivity(), OpinionActivity.class)));
    }

    private void initRefresh() {
        if (getActivity() != null) {
            refreshLayout = view.findViewById(R.id.refreshLayout);
            // 开启自动加载功能
            refreshLayout.setEnableHeaderTranslationContent(true);
            //设置 Header 为 贝塞尔雷达 样式
            refreshLayout.setRefreshHeader(new BezierRadarHeader(getActivity()).setPrimaryColorId(R.color.main).setEnableHorizontalDrag(true));

//            refreshLayout.setRefreshFooter(new FalsifyFooter(getActivity()));
            refreshLayout.setRefreshFooter(new BallPulseFooter(getActivity()).setAnimatingColor(getActivity().getColor(R.color.main)));
            // 下拉刷新
            refreshLayout.setOnRefreshListener(mLayout -> this.getMatterList(true, mLayout::finishRefresh));
            // 上拉加载
            refreshLayout.setOnLoadMoreListener(mLayout -> {
                page++;
                this.getMatterList(false, boo -> {
                    mLayout.finishLoadMore(boo);
                    if (!boo) {
                        mLayout.finishLoadMoreWithNoMoreData();//将不会再次触发加载更多事件
                    }
                });
            });
        }
    }

    private void initData() {
        if (getActivity() != null) {
            SharedPreferences preferences = getActivity().getSharedPreferences("userInfo", MODE_PRIVATE);
            String customerStr = preferences.getString("customer", "");
            Gson gson = new Gson();
            if (!StrUtil.hasBlank(customerStr)) {
                Customer customer = gson.fromJson(customerStr, Customer.class);
                nickNameText.setText(customer.getNickName());
                Glide.with(getActivity()).load(customer.getHeadImg()).into(pictureImgView);

                // 计算时间间隔
                Duration between = LocalDateTimeUtil.between(customer.getCreateTime(), LocalDateTime.now());
                cardNumText.setText(format(Locale.CHINA, "坚持打卡的第%d天", between.toDays()));
            }
        }
    }

    // 获取个人信息，主要是更新信息
    private void getPersonMeInfo() {
        Type type = new TypeToken<Result<Customer>>() {
        }.getType();
        OkHttpUtils.getInstance().get(getActivity(), RequestEnum.GET_ME_INFO, type, false, (Consumer<Customer>) customer -> {
            if (getActivity() != null) {
                getActivity().runOnUiThread(() -> {
                    PersonDataBase.setPersonInfo(getActivity(), customer);
                    initData();
                });
            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();
        initData();
        getPersonMeInfo();
//        refreshLayout.autoRefresh();
        getMatterList(true, aBoolean -> {
        });
    }

    /**
     * 获取我的每日记录列表
     */
    private void getMatterList(boolean isFirst, Consumer<Boolean> booleanConsumer) {
        Type type = new TypeToken<Result<List<MatterListVO>>>() {
        }.getType();
        if (isFirst) {
            page = 0;
            this.matterList = new ArrayList<>();
        }
        String url = OkHttpUtils.BASE_URL + "/api/v1/matter/search/" + page;
        if (getActivity() != null) {
            OkHttpUtils.getInstance().get(getActivity(), url, type, false, (Consumer<List<MatterListVO>>) voList -> {
                if (voList.size() == 0) {
                    // TODO 显示暂无记录
                    if (getActivity() != null) {
                        booleanConsumer.accept(false);
                    }
                } else {
                    this.matterList.addAll(voList);
                }
                if (getActivity() != null) {
                    // 不传参数代表刷新成功，传数字代表延迟，传false代表更新失败
                    getActivity().runOnUiThread(() -> {
                        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
                        matterListView.setLayoutManager(layoutManager);
                        ListMatterAdapter2 adapter = new ListMatterAdapter2(getActivity(), this.matterList, aBoolean -> {
                            getActivity().runOnUiThread(() -> getMatterList(true, aBoolean1 -> booleanConsumer.accept(true)));
                        });
                        adapter.setItemAnimation(BaseQuickAdapter.AnimationType.AlphaIn);
                        matterListView.setAdapter(adapter);
                        booleanConsumer.accept(true);
                    });
                }
            });
        }
    }

    private void initView() {
        pictureImgView = view.findViewById(R.id.picture_img_view);
        nickNameText = view.findViewById(R.id.nick_name_text);
        cardNumText = view.findViewById(R.id.card_num_text);
        matterListView = view.findViewById(R.id.matter_list_view);
        FloatingActionButton addBtn = view.findViewById(R.id.add_btn);
        addBtn.setOnClickListener(v -> addBottomDialog());
        LinearLayout personLayout = view.findViewById(R.id.top_layout_person);
        personLayout.setOnClickListener(v -> {
            new BottomSheet.BottomListSheetBuilder(getActivity())
                    .addItem("修改头像/昵称")
                    .addItem("修改密码")
                    .addItem("邀请好友协作")
                    .setIsCenter(true)
                    .setOnSheetItemClickListener((dialog, itemView, position, tag) -> {
                        dialog.dismiss();
                        if (getActivity() != null) {
                            if (position == 0) {
                                getActivity().startActivity(new Intent(getActivity(), UpdatePersonMeActivity.class));
                            } else if (position == 1) {
                                getActivity().startActivity(new Intent(getActivity(), UpdatePasswordActivity.class));
                            } else if (position == 2) {
                                getActivity().startActivity(new Intent(getActivity(), ShareCodeActivity.class));
                            }
                        }
                    }).build().show();
        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == REQUEST_CODE_SCAN && resultCode == RESULT_OK) {
            // 处理二维码扫描结果
            handleScanResult(data);
        } else if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK) {
            // 用户选择图片识别二维码
            Uri imageUri = data.getData();
            getAnalyzeQRCodeResult(imageUri);
        }
    }

    /**
     * 调用系统相册，如果没给权限，动态获取
     */
    private void showFileChooser() {
        // 如果当前用户没给权限，则弹出权限申请
        if (getActivity() != null) {
            if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE);
            } else {
                Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                intent.setType("image/**");
                startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
            }
        }
    }

    /**
     * 动态获取权限回调
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // 执行打开相册的操作
                Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(intent, PICK_IMAGE_REQUEST);
            } else {
                if (getActivity() != null) {
                    new MaterialDialog.Builder(getActivity()).iconRes(R.drawable.icon_error_24).title(R.string.error)
                            .content("您拒绝了系统获取文件的权限，请前往设置打开‘读写手机存储’权限")
                            .positiveText(R.string.yes).onPositive((dialog, which) -> {
                                Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                                intent.setData(Uri.fromParts("package", getActivity().getPackageName(), null));
                                startActivity(intent);
                            }).show();
                }
            }
        }
    }

    /**
     * 处理二维码扫描结果
     *
     * @param data
     */
    private void handleScanResult(Intent data) {
        if (data != null) {
            Bundle bundle = data.getExtras();
            if (getActivity() != null && bundle != null) {
                if (bundle.getInt(XQRCode.RESULT_TYPE) == XQRCode.RESULT_SUCCESS) {
                    String result = bundle.getString(XQRCode.RESULT_DATA);
                    if (result.contains(PersonDataBase.ADD_FRIEND_KEY)) {
                        // 添加好友
                        result = result.replace(PersonDataBase.ADD_FRIEND_KEY, "");
                        sendAddFriend(result);
                    }
                } else if (bundle.getInt(XQRCode.RESULT_TYPE) == XQRCode.RESULT_FAILED) {
                    XToast.info(getActivity(), "解析失败").show();
                }
            }
        }
    }

    /**
     * 发送添加好友请求
     *
     * @param code 好友请求码
     */
    private void sendAddFriend(String code) {

        // 1.先查询好友信息
        Type decodeType = new TypeToken<Result<AddFriendShare>>() {}.getType();
        String decodeUrl = OkHttpUtils.BASE_URL + "/api/v1/friendship/decode/friend/info?code=" + code;
        OkHttpUtils.getInstance().get(getActivity(), decodeUrl, decodeType, true, (Consumer<AddFriendShare>) addFriendShare -> {
            if (addFriendShare != null && getActivity() != null) {
                getActivity().runOnUiThread(() -> {
                    new MaterialDialog.Builder(getActivity()).iconRes(R.drawable.icon_info).title(R.string.info)
                            .content("您确定要添加'" + addFriendShare.getNickName() + "'为协作人吗？").positiveText(R.string.yes).negativeText(R.string.cancel)
                            .onPositive((dialog, which) -> {
                                Type type = new TypeToken<Result<Boolean>>() {}.getType();
                                String url = OkHttpUtils.BASE_URL + "/api/v1/friendship/add?code=" + code;
                                OkHttpUtils.getInstance().get(getActivity(), url, type, true, (Consumer<Boolean>) b -> {
                                    if (b && getActivity() != null) {
                                        getActivity().runOnUiThread(() -> {
                                            XToast.success(getActivity(), "好友添加成功").show();
                                        });
                                    }
                                });
                            }).show();
                });
            }
        });
    }

    /**
     * 进行二维码解析
     *
     * @param uri
     */
    private void getAnalyzeQRCodeResult(Uri uri) {
        XQRCode.analyzeQRCode(PathUtils.getFilePathByUri(getContext(), uri), new QRCodeAnalyzeUtils.AnalyzeCallback() {
            @Override
            public void onAnalyzeSuccess(Bitmap mBitmap, String result) {
                if (getActivity() != null) {
                    if (result.contains(PersonDataBase.ADD_FRIEND_KEY)) {
                        // 添加好友
                        result = result.replace(PersonDataBase.ADD_FRIEND_KEY, "");
                        sendAddFriend(result);
                    } else {
                        new MaterialDialog.Builder(getActivity()).iconRes(R.drawable.icon_error_24).title(R.string.error).content("'" + getActivity().getString(R.string.app_name) + "'暂时无法识别来自外部的二维码").positiveText(R.string.yes).show();
                    }
                }
            }

            @Override
            public void onAnalyzeFailed() {
                ToastUtils.toast("解析二维码失败", Toast.LENGTH_LONG);
            }
        });
    }

    public void addBottomDialog() {
        System.out.println("addBottomDialog");
        if (getActivity() != null) {
            final int[] iconPosition = {0};
            BottomSheetDialog bottomSheetDialog = new BottomSheetDialog(getActivity(), R.style.bottom_sheet_dialog);
            View bottomSheetView = LayoutInflater.from(getActivity()).inflate(R.layout.dialog_bottom_add_matter, null);

            bottomSheetDialog.setContentView(bottomSheetView);
            bottomSheetDialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);

            // 获取布局中的控件
            EditText editText = bottomSheetView.findViewById(R.id.title_edit);
            Button addButton = bottomSheetView.findViewById(R.id.button);
            TextView iconText = bottomSheetView.findViewById(R.id.icon_text);
            TextView goCreateText = bottomSheetView.findViewById(R.id.go_desc_create_text);
            iconText.setText(iconStrItems[iconPosition[0]]);

            editText.requestFocus();

            editText.setOnEditorActionListener((v, actionId, event) -> {
                if (actionId == EditorInfo.IME_ACTION_DONE) { // 点击完成按钮
                    String title = editText.getText().toString();
                    if (getActivity() != null) {
                        if (StrUtil.hasBlank(title)) {
                            return false;
                        }
                        AddMatterParam matterParam = new AddMatterParam();
                        matterParam.setDateTxt(DateUtil.format(new Date(), "yyyyMMdd"));
                        matterParam.setIcon(String.valueOf(iconPosition[0]));
                        matterParam.setRemark("");
                        matterParam.setTitle(title);
                        Type type = new TypeToken<Result<Matter>>() {
                        }.getType();
                        OkHttpUtils.getInstance().post(getActivity(), RequestEnum.ADD_MATTER, type, matterParam, true, (Consumer<Matter>) matter1 -> {
                            if (getActivity() != null) {
                                getActivity().runOnUiThread(() -> {
                                    bottomSheetDialog.dismiss();
                                    getMatterList(true, aBoolean -> {
                                    });
                                });
                            }
                        });
                    }
                    return true;
                }
                return false;
            });

            // 设置按钮点击事件
            addButton.setOnClickListener(v -> {
                String title = editText.getText().toString();
                if (getActivity() != null) {
                    if (StrUtil.hasBlank(title)) {
                        XToast.error(getActivity(), "事件名称不可为空").show();
                        return;
                    }
                    AddMatterParam matterParam = new AddMatterParam();
                    matterParam.setDateTxt(DateUtil.format(new Date(), "yyyyMMdd"));
                    matterParam.setIcon(String.valueOf(iconPosition[0]));
                    matterParam.setRemark("");
                    matterParam.setTitle(title);
                    Type type = new TypeToken<Result<Matter>>() {
                    }.getType();
                    OkHttpUtils.getInstance().post(getActivity(), RequestEnum.ADD_MATTER, type, matterParam, true, (Consumer<Matter>) matter1 -> {
                        if (getActivity() != null) {
                            getActivity().runOnUiThread(() -> {
                                bottomSheetDialog.dismiss();
                                getMatterList(true, aBoolean -> {
                                });
                            });
                        }
                    });
                }
            });

            iconText.setOnClickListener(v -> {
                // 选择事件类型
                XUISimpleAdapter adapter = XUISimpleAdapter.create(getActivity(), iconStrItems);
                XUIListPopup mListPopup = new XUIListPopup(getActivity(), adapter);
                mListPopup.create(DensityUtils.dp2px(getActivity(), 90), DensityUtils.dp2px(getActivity(), 200), (parent, view1, position, id) -> {
                    iconPosition[0] = position;
                    iconText.setText(iconStrItems[iconPosition[0]]);
                    System.out.println("----------------");
                    System.out.println(iconPosition[0]);
                    mListPopup.dismiss();
                });
                mListPopup.setAnimStyle(XUIPopup.ANIM_GROW_FROM_CENTER);
                mListPopup.setPreferredDirection(XUIPopup.DIRECTION_TOP);
                mListPopup.show(v);
            });

            goCreateText.setOnClickListener(v -> {
                // 跳转到详细创建界面
                if (getActivity() != null) {
                    bottomSheetDialog.dismiss();
                    getActivity().startActivity(new Intent(getActivity(), AddMatterActivity.class));
                }
            });

            // 显示底部弹出框
            bottomSheetDialog.show();
        }
    }
}
